#include "breathing_led.h"
#include "pico/stdlib.h"
#include "hardware/gpio.h"
#include "hardware/pwm.h"
#include <stdio.h>
#include <math.h>
#include "LOG.h"
#include "board.h"

// PWM相关变量
static uint slice_num = 0;
static uint chan = 0;
static uint8_t pwm_gpio_num = BREATHING_PWM_GPIO;

// 呼吸灯状态变量
static uint16_t step = 0;
static uint32_t cycle_count = 0;
static float brightness_f = 0.0f;

// 模式控制变量
static BreathingMode_t current_mode = CONSTANT_MODE;
static uint16_t constant_brightness = 0;

// 计算呼吸灯亮度值的函数
static uint16_t calculate_breathing_brightness(uint16_t step, float *brightness_f) {
    // 使用改进的缓动函数，避免0附近的突变
    float angle = (float)step * 2.0f * 3.14159265f / (float)BREATHING_TOTAL_STEPS;
    
    // 使用缓动函数：(1 - cos(x)) / 2，在边界处变化更平滑
    float eased_value = (1.0f - cosf(angle)) / 2.0f;  // 0-1之间平滑变化
    
    // 设置最小亮度为5%（约62），避免LED完全熄灭造成跳跃感
    // 使用宏定义的最大亮度值
    const uint16_t max_brightness = BREATHING_MAX_BRIGHTNESS - BREATHING_MIN_BRIGHTNESS;
    
    *brightness_f = BREATHING_MIN_BRIGHTNESS + eased_value * max_brightness;
    
    // 确保在有效范围内
    uint16_t brightness = (uint16_t)(*brightness_f + 0.5f);
    if (brightness > 1249) brightness = 1249;
    
    return brightness;
}

// 呼吸灯处理函数（替代原来的任务）
void breathing_led_process(void)
{
    // 根据当前模式执行相应操作
    if (current_mode == BREATHING_MODE) {
        // 计算当前亮度值
        uint16_t brightness = calculate_breathing_brightness(step, &brightness_f);

        // 每30步打印一次详细信息
        if (step % 30 == 0)
        {
            float eased_value = (1.0f - cosf((float)step * 2.0f * 3.14159265f / (float)BREATHING_TOTAL_STEPS)) / 2.0f;
            LOG_DEBUG("Breathing process - step %d: eased=%.3f, brightness=%d (%.1f)",
                      step, eased_value, brightness, brightness_f);
        }

        // 设置PWM占空比
        pwm_set_chan_level(slice_num, chan, brightness);

        // 每完成一个完整周期打印一次统计信息
        if (step == 0 && cycle_count > 0)
        {
            LOG_INFO("Breathing process - cycle %d completed (min brightness: %d)",
                     cycle_count, BREATHING_MIN_BRIGHTNESS);
        }

        // 更新步进
        step++;
        if (step >= BREATHING_TOTAL_STEPS)
        {
            step = 0;
            cycle_count++;
        }
    } else {
        // 固定亮度模式，直接设置亮度
        pwm_set_chan_level(slice_num, chan, constant_brightness);
    }
}

// 初始化PWM硬件
static bool led_pwm_init(uint8_t gpio)
{
    LOG_INFO("PWM_init - Initializing PWM on GPIO%d", gpio);
    
    // 设置GPIO为PWM功能
    LOG_INFO("  - Setting GPIO%d to PWM function", gpio);
    gpio_set_function(gpio, GPIO_FUNC_PWM);
    
    // 获取GPIO对应的PWM slice和channel
    slice_num = pwm_gpio_to_slice_num(gpio);
    chan = pwm_gpio_to_channel(gpio);
    LOG_INFO("  - GPIO%d mapped to PWM slice %d, channel %d", gpio, slice_num, chan);
    
    // 设置PWM频率为100kHz
    LOG_INFO("  - Setting PWM frequency to 100kHz (wrap=1249)");
    pwm_set_wrap(slice_num, 1249);  // 0-1249 = 1250个周期
    
    // 初始占空比0%
    LOG_INFO("  - Setting initial duty cycle to 0%%");
    pwm_set_chan_level(slice_num, chan, 0);
    
    // 启用PWM
    LOG_INFO("  - Enabling PWM slice %d", slice_num);
    pwm_set_enabled(slice_num, true);
    LOG_INFO("PWM_init completed successfully");
    
    return true;
}

// 设置为呼吸模式
void breathing_led_set_breathing_mode(void) {
    current_mode = BREATHING_MODE;
}

// 设置为固定亮度模式
void breathing_led_set_constant_mode(uint16_t brightness) {
    current_mode = CONSTANT_MODE;
    constant_brightness = brightness;
    
    // 确保亮度在有效范围内
    if (constant_brightness > 1249) constant_brightness = 1249;
}

// 获取当前模式
BreathingMode_t breathing_led_get_mode(void) {
    return current_mode;
}

// 初始化呼吸灯模块
bool breathing_led_init(void)
{  
    // 默认设置为固定亮度模式
    current_mode = CONSTANT_MODE;
    constant_brightness = 0;
    
    return led_pwm_init(BREATHING_PWM_GPIO);
}
